/******************************************************************************************************
Copyright (C) 2013 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

/*globals Application, MessageBox, qsTr, DBPlugin, ProgressDialog, print, MnUi*/
/*jslint plusplus: true, indent: 4*/

function dbImportPages() {
	"use strict";
	// Check we have something to store
    var p, db, progress, page, items, i, item, recid,
		dw = Application.mainWindow.activeDocument,
		itemCount = 0,
		pageCount = 0;
	if (dw.itemCount() === 0) {
		return MessageBox.critical(qsTr("No items in document - nothing to import."));
	}

	// Check for ambiguous molecules
	for (p = 0; p < dw.pageCount(); p++) {
		if (dw.page(p).itemCount("Molecule") > 1) {
			return MessageBox.critical(qsTr("More than one molecule on page {0} - aborting import.").format(p + 1));
		}
		if (dw.page(p).itemCount() > 0) {
			pageCount++;
		}
		itemCount += dw.page(p).itemCount();
	}

	// Choose database
	Application.mainWindow.doAction("dbDatabaseOpen");
	db = DBPlugin.client;
	if (!db.connected()) {
		return;
	}

	// Last chance to bail out
	if (MessageBox.question(qsTr("Database <b>{0}</b>: Import {1} items into {2} new records?").format(db.database, itemCount, pageCount), MessageBox.Yes, MessageBox.Cancel) !== MessageBox.Yes) {
		return;
	}

	progress = new ProgressDialog();
	progress.setRange(0, pageCount);
	progress.labelText = qsTr("Creating records...");
	progress.show();

	// Store items
	itemCount = 0;
	pageCount = 0;
	for (p = 0; p < dw.pageCount(); p++) {
		if (progress.wasCanceled || !db.connected()) {
			break;
		}

		// Update progress dialog
		progress.value = pageCount;

		// Save all items in page to a new record
		page = dw.page(p);
		items = [];
		for (i = 0; i < page.itemCount(); i++) {
			item = page.item(i);
			print(" Item " + i + ": " + item);
			items.push(item);
		}
		print("Saving...");
		recid = DBPlugin.addRecord(db, items);
		if (recid <= 0) {
			MessageBox.critical(qsTr("Error while saving items on page {0}.").format(p + 1));
		} else {
			progress.labelText = qsTr("Saved {0} items under record id {1}.").format(items.length, recid);
			print("Saved " + items.length + " items under record id " + recid + ".");
			itemCount += items.length;
			pageCount += 1;
		}
	}
	MessageBox.information(qsTr("Saved {0} items to {1} new records.").format(itemCount, pageCount));
	progress.close();
}

if (this.MnUi && MnUi.scripts_db) {
	MnUi.scripts_db.scripts_db_ImportPages = dbImportPages;
}
